<script setup>
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { ref,onMounted } from 'vue'
import Info from './info.vue'
// import AssignRole from './components/assignRole.vue'

import { useConfirm } from '@/hooks/useConfirm'

// import tableData from '~mock/user'
import {getUserList,deleteUser,exportUserExcel,updateUser} from '@/api/user'

// 表单状态
const filterState = ref(true)
// 表单数据
const isExpand = ref(false)
const formData = ref({
  pageNum: 1,
  size: 10,
  pageSize:10

  // role_name: '',
  // created_at: '',
  // updated_at: '',

  // created_at_temp: [], // el-date-picker组件保存是数组
  // updated_at_temp: [] // el-date-picker组件保存是数组
})

const tableData=ref({})
// 从接口获取数据
const getUserListData = async () => {
  // if (dateRange.value.length) {
  //   //赋值
  //   formData.value.startDate = dateRange.value[0]
  //   formData.value.endDate = dateRange.value[1]
  // }
  try {
    // Object.assign({}, formData, startDate, endDate)


    const r = await getUserList(formData.value)
    if (r.code == 200) {
      tableData.value = r.data
      ElMessage({
        type: 'success',
        message: '获取列表成功'
      })
    } else {
      ElMessage.error(r.data.msg)
    }
  } catch {
    ElMessage.error('请稍后再试')
  }
}
onMounted(()=>{
  getUserListData()
  
})
// // 分页
// const onSizeChange = (val) => {
//   console.log(`${val} items per page`)
// }
// const onCurrentChange = (val) => {
//   console.log(`current page: ${val}`)
// }
// 分页
const onSizeChange = (val) => {
  formData.value.size = val
  formData.value.pageSize = val
  getUserListData()
}
const onCurrentChange = (val) => {
  formData.value.pageNum = val
  getUserListData()
}
// 用户编辑
const infoRef = ref()
const onUserInfo = (row) => {
  infoRef.value.state = true
  if (row) {
    infoRef.value.formData = row
  }
}

// 用户删除
const onDelete = (row) => {
  ElMessageBox.confirm('确定删除该条数据吗?', '温馨提示', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      //请求删除接口
      let r=await deleteUser({id:row.id})
      if(r.code==200){
        ElMessage({type: 'success', message: '删除成功' })
        getUserListData()
      }else{
        ElMessage({type: 'info', message: r.data})
      }
    })
    .catch(() => {
      ElMessage({type: 'info', message: '删除取消' })
    })
  }


const userState = ref('')
const userStateOption = [
  {
    value: 1,
    label: '正常'
  },
  {
    value: 0,
    label: '禁用'
  }
]

// 批量选择
let ids = ref([])
const onSelectionChange = (val) => {
  ids.value = val
}

const search = ()=>{
  getUserListData()
}
const resetSearch = ()=>{
  formData.value = {
    pageNum: 1,
    size: 10,
    pageSize:10
  }
  getUserListData()
}
const exportUser = async()=>{
  
  const res = await exportUserExcel(formData.value)
  downloadFile(res,"user")
}

// 文件流解析并下载
function downloadFile(res,list_name) {
  let link = document.createElement("a");
  //    type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
  let blogw = new Blob([res], {
    type: "application/vnd.ms-excel;charset=utf-8",
  });
  let objectUrl = window.URL.createObjectURL(blogw); // 创建一个新的url对象
  link.href = objectUrl;
  link.download = list_name; //  下载的时候自定义的文件名
  link.click();
  window.URL.revokeObjectURL(objectUrl);

}
const isImport = ref(false)
const importUser=(r)=>{
  if(r.code==200){
    isImport.value=false;
    getUserListData();
  }
}
const updateState=(id,state)=>{
  let data = {
    id : id,
    state : state
  }
  updateUser(data).then(res=>{
    console.log(res)
  })
}

</script>
<template>
  <Box>
    <!-- 逻辑层 -->
    <Info ref="infoRef"   @flush="getUserListData"/>
    <!-- <AssignRole ref="assignRoleRef" /> -->
    <!-- 逻辑层 -->

    <!-- 筛选 -->
    <template #filter v-if="filterState">
      <el-form :inline="true" :model="formData">
        <el-form-item label="用户名称">
          <el-input placeholder="请输入用户名称" v-model="formData.userName" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请输入手机号码" v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.userState" placeholder="用户状态" style="width: 120px">
            <el-option
              v-for="item in userStateOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建于" v-show="isExpand">
          <el-date-picker
            v-model="formData.created_at_temp"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"> <span class="iconfont icon-sousuo" ></span>搜索 </el-button>
          <el-button type="default" @click="resetSearch"> 重置 </el-button>
          <el-button type="primary" link @click="isExpand = !isExpand">
            {{ isExpand ? '收起' : '展开' }}
            <el-icon>
              <ArrowUp v-if="isExpand" />
              <ArrowDown v-else />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <!-- 筛选 -->
    <!-- 内容 -->
    <!-- 按钮组 -->
    <el-row>
      <el-col :span="12">
        <el-button type="primary" @click="onUserInfo(0)">
          <span class="iconfont icon-jiahao"></span>添加
        </el-button>
        <el-button type="danger" :disabled="!ids.length">
          <span class="iconfont icon-shanchu" @click="onUserInfo(0)"></span>删除
        </el-button>
        <el-button type="info" @click="isImport=true">
          <span class="iconfont icon-shangchuan"></span>导入
        </el-button>
        
        <el-button type="warning" @click="exportUser">
          <span class="iconfont icon-xiazai-"></span>导出
        </el-button>
      </el-col>

      <el-col :span="12" style="text-align: right">
        <el-button circle @click="filterState = !filterState">
          <span class="iconfont icon-sousuo"></span>
        </el-button>
        <el-button circle  @click="getUserListData">
          <span class="iconfont icon-shuaxin"></span>
        </el-button>
      </el-col>
    </el-row>
    <!-- 按钮组 -->
    <!-- 表格 -->
    <el-table :data="tableData.list" :border="true" @selection-change="onSelectionChange">
      <el-table-column type="selection" align="center" fixed="left"></el-table-column>
      <el-table-column label="用户编号" prop="id" align="center" width="60"></el-table-column>
      <el-table-column label="用户名" prop="userName" align="center"   width="100"></el-table-column>
      <!-- <el-table-column label="用户名" prop="uname" align="center" width="200"></el-table-column> -->
      <el-table-column label="用户名称" prop="empName" align="center" width="160"></el-table-column>
      <el-table-column label="种类" prop="type" align="center" width="120">
        <template #default="scoped" >
          <el-tag v-if="parseInt(scoped.row.type) === 0">管理员</el-tag>
          <el-tag type="success" v-else>普通用户</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="type" label="类型" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 0" type="warning">一级</el-tag>
          <el-tag v-if="scope.row.type === 1" type="info">二级</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        label="所属角色"
        prop="roleName"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center" width="180"></el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scoped">
          <el-switch
            v-model="scoped.row.state"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="正常"
            inactive-text="禁用"
            :active-value="0"
            :inactive-value="1"
            @change='updateState(scoped.row.id,scoped.row.state)'
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建于"
        prop="createTime"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scoped">
          <el-button type="primary" link size="small" @click="onUserInfo(scoped.row)">
            <span class="iconfont icon-bianji"></span>修改
          </el-button>
          <el-button type="primary" link size="small" @click="onDelete(scoped.row)">
            <span class="iconfont icon-shanchu"></span>删除
          </el-button>
          <!-- <el-button type="primary" link size="small" @click="onAssignRole(scoped.row)">
            <span class="iconfont icon-gengduo"></span>
            分配角色
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格 -->
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="formData.pageNum"
      v-model:page-size="formData.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    />
    <!-- 分页 -->
    <!-- 内容 -->
  </Box>
  <el-dialog v-model="isImport" title="上传用户Excel文件" width="500">
      <el-upload
          class="upload-demo"
          drag
          :on-success="importUser"
          action="http://127.0.0.1:8080/sys/user/import"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          请把上传的Excel拖拽到这里 <em>或者点击选择上传的文件</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            Excel只支持xlxs格式的文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
</template>
